#include "App.h"
#include "can_lib.h"
#include "app_input.h"

uint8_t  uc_timeout_start_sn  = 0;/*计数开始*/
uint32_t ul_timeout_count_cnt = 0;/*计数值*/

void App_tick_update(void)
{

}
/**
 * @brief 按键板16个按键定义
 */
uint8_t uc_keyboard_key01 = 0;
uint8_t uc_keyboard_key02 = 0;
uint8_t uc_keyboard_key03 = 0;
uint8_t uc_keyboard_key04 = 0;

uint8_t uc_keyboard_key05 = 0;
uint8_t uc_keyboard_key06 = 0;
uint8_t uc_keyboard_key07 = 0;
uint8_t uc_keyboard_key08 = 0;

uint8_t uc_keyboard_key09 = 0;
uint8_t uc_keyboard_key10 = 0;
uint8_t uc_keyboard_key11 = 0;
uint8_t uc_keyboard_key12 = 0;

uint8_t uc_keyboard_key13 = 0;
uint8_t uc_keyboard_key14 = 0;
uint8_t uc_keyboard_key15 = 0;
uint8_t uc_keyboard_key16 = 0;

/**
 * @brief CAN ID号注册
 */
void can_register_id_Callback(void)
{
    uint32_t id_buf[4] = {0x104,0x283};
    uint32_t std_id_buf[7] = {0x585,0x181,0x182,0x183,0x581,0x582,0x583};
    CAN_Std_List_Filter(7,id_buf);
    CAN_Std_Mask_Filter(8,std_id_buf,7);
}
uint32_t ul_can_rx_cnt      = 0;/*CAN 接收报文计数*/
uint32_t ul_can_rx_cnt_last = 0;
uint8_t can_rx_keyboard_buf[8]  = { 0 };
/**
 * @brief 例：CAN接收0x04的ID号数据，该函数只需要放到
 * can_rx_data_Callback函数中
 */
void can_rx_id_0x104(can_receive_message_struct *buf)
{
  if(buf->rx_ff != CAN_FF_STANDARD) return;   //标准帧判断
  if(buf->rx_sfid != 0x104) return;             //ID号判断
 
  memcpy(can_rx_keyboard_buf,buf->rx_data,buf->rx_dlen);

  ul_can_rx_cnt++;
}

/**
 * @brief 
 */
void can_rx_data_Callback(can_receive_message_struct *buf)
{
  can_rx_id_0x104(buf);
}

uint8_t uc_can_rx_anomalous_cnt = 0;/*CAN接收异常计数*/
uint8_t uc_can_rx_anomalous_status = 0;/*CAN接收异常标志，1-CAN超过500ms没有接收到报文*/
/**
 * @brief CAN接收异常判断，可以放在发送函数中，也可以放到100ms定时器中
 */
void App_can_rx_anomalous(void)
{
  if(ul_can_rx_cnt != ul_can_rx_cnt_last)
  {
    ul_can_rx_cnt_last = ul_can_rx_cnt;
    uc_can_rx_anomalous_cnt = 0;
    uc_can_rx_anomalous_status = 0;
  }
  else
  {
    uc_can_rx_anomalous_cnt++;
  }

  if(uc_can_rx_anomalous_cnt > 5)
  {
    uc_can_rx_anomalous_status = 1;
  }
}
uint8_t uc_can_tx_sn = 0;/*CAN发送时间标志*/
/**
 * @brief CAN 发送给按键板的报文
 */
void App_can_tx(void)
{
  uint8_t buf[8] = { 0 };

  if(uc_can_tx_sn == 0) return;
  uc_can_tx_sn = 0;

  buf[0] = uc_keyboard_key01 | uc_keyboard_key02;
  buf[1] = uc_keyboard_key03 | uc_keyboard_key04;
  buf[2] = uc_keyboard_key05 | uc_keyboard_key06;
  buf[3] = uc_keyboard_key07 | uc_keyboard_key08;
  buf[4] = uc_keyboard_key09 | uc_keyboard_key10;
  buf[5] = uc_keyboard_key11 | uc_keyboard_key12;
  buf[6] = 0;
  buf[7] = 0;
  Can_Data_Store_Fifo(0x105,0,buf,8);

  App_can_rx_anomalous();
}

void App_run(void)
{
	App_can_tx();
}





